package com.codeplay.service.impl;

import com.codeplay.entity.Course;
import com.codeplay.repository.CourseRepository;
import com.codeplay.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CourseServiceImpl implements CourseService {

    private final CourseRepository courseRepository;

    @Autowired
    public CourseServiceImpl(CourseRepository courseRepository) {
        this.courseRepository = courseRepository;
    }

    @Override
    public Course createCourse(Course course) {
        return courseRepository.save(course);
    }

    @Override
    public Course getCourseById(Long id) {
        return courseRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Course not found"));
    }

    @Override
    public Page<Course> getAllCourses(Pageable pageable) {
        return courseRepository.findAll(pageable);
    }

    @Override
    public Page<Course> getCoursesByDifficultyLevel(Course.DifficultyLevel difficultyLevel, Pageable pageable) {
        return courseRepository.findByDifficultyLevel(difficultyLevel, pageable);
    }

    @Override
    public Page<Course> getCoursesByAgeRange(String ageRange, Pageable pageable) {
        return courseRepository.findByAgeRange(ageRange, pageable);
    }

    @Override
    public List<Course> getCoursesByCreator(Long creatorId) {
        return courseRepository.findByCreatedById(creatorId);
    }

    @Override
    public Page<Course> searchCourses(String keyword, Pageable pageable) {
        return courseRepository.findByTitleContainingIgnoreCase(keyword, pageable);
    }

    @Override
    public Course updateCourse(Course course) {
        Course existingCourse = getCourseById(course.getId());
        existingCourse.setTitle(course.getTitle());
        existingCourse.setDescription(course.getDescription());
        existingCourse.setCoverImage(course.getCoverImage());
        existingCourse.setDifficultyLevel(course.getDifficultyLevel());
        existingCourse.setAgeRange(course.getAgeRange());
        return courseRepository.save(existingCourse);
    }

    @Override
    public void deleteCourse(Long id) {
        courseRepository.deleteById(id);
    }
} 